<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Models\Shop;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;
use App\Http\Requests\Admin\Shop\StoreRequest;
use App\Http\Requests\Admin\Shop\UpdateRequest;
use App\Models\Goods;
use Gate;
use App\Exceptions\Admin\PermissionDeniedException;
use App\Commands\OperationLogCommand;
use App\Models\ShopUser;
use App\Models\User;

class ShopController extends Controller
{

    public function shop_gate()
    {
        if (!Gate::allows('shop','')) {
            throw new PermissionDeniedException();
        }//end if()

    }//end func __construce()

    public function index(Request $request)
    {
        $this->shop_gate();

        $search = array('shop_name'=>'');
        $shop = Shop::orderBy('sort_order','desc');
        if (!empty($request->get('shop_name'))){
            $shop = $shop->where('shop_name', 'like', "%".trim($request->get('shop_name'))."%");
            $search['shop_name'] = $request->shop_name;
        }//end if()
        $shop = $shop->paginate(10);

        return view('admin.shop.index',compact('shop','search'));
    }


    public function create(Shop $shop)
    {
        $this->shop_gate();

        $users = User::all();

        $user_arr = [];

        foreach ($users as $key => $user) {

            $user_arr[$user->id] = $user->user_name;
            // $user_arr[$user->id] = $user->phone;
        }

        return view('admin.shop.create',compact('shop', 'user_arr'));
    }


    public function store(StoreRequest $request,Shop $shop)
    {

        $this->shop_gate();

        $param = $request->all();

        $shop = $shop->create($param);
        $this->dispatch(
            new OperationLogCommand('添加商铺','Shop','id:'.$shop->id)
        );

        //如果创建商铺成功，则将商铺id和对应的用户id存入shop_user表
        // $request->use_id_str = '59, 60';                          //noPro
        if ($request->use_id_str) {

            $user_arr = explode(',', $request->use_id_str);        //将用户id集合字符串分割为数组

            if ($shop) {

                foreach ($user_arr as $key => $user_id) {

                    $shopUsers = ShopUser::where('user_id', $user_id)->first();

                    if ($shopUsers) {

                        continue;
                    }

                    ShopUser::create(['shop_id'=>$shop->id, 'user_id'=>$user_id]);
                }
            }
        }

        return Redirect('admin/shop');
    }

    /**
     * 获取商铺
     *
     * @date 2016/04/19
     * @author Leen
     */
    public function show($id)
    {

        $this->shop_gate();

        $shop = Shop::orderBy('sort_order','desc');

        $shop = $shop->get();

        return $shop;
    }//end func show()

     /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $shop_id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $this->shop_gate();

        $shop = Shop::find($id);

        $users = User::all();

        $user_arr = [];

        foreach ($users as $key => $user) {

            $user_arr[$user->id] = $user->user_name;
        }


        $shopUser = ShopUser::where('shop_id', $id)

                    ->leftJoin('user', 'shop_user.user_id', '=', 'user.id' )

                    ->get();

        return view('admin.shop.edit',compact('shop', 'user_arr', 'shopUser'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(UpdateRequest $request, $id)
    {
        $this->shop_gate();

        $shop = Shop::find($id);
        $shop->update($request->all());
        $this->dispatch(
            new OperationLogCommand('修改商铺','Shop','id:'.$id)
        );

        //如果创建商铺成功，则将商铺id和对应的用户id存入shop_user表
        // $request->use_id_str = '59, 61';                          //noPro
        if ($request->use_id_str) {

            $user_arr = explode(',', $request->use_id_str);        //将用户id集合字符串分割为数组

            if ($shop) {

                $shop_user = ShopUser::where('shop_id', $id)->delete();

                foreach ($user_arr as $key => $user_id) {

                    $shopUsers = ShopUser::where('user_id', $user_id)->first();

                    if ($shopUsers) {

                        continue;
                    }

                    ShopUser::create(['shop_id'=>$shop->id, 'user_id'=>$user_id]);
                }
            }
        }

        return Redirect($request->get('back_url'));
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {

        $this->shop_gate();

        $goods = Goods::where('shop_id', $id)->first();

        if(empty($goods)){

            $shop = Shop::find($id);

            $shop->delete();
            $this->dispatch(
                new OperationLogCommand('删除商铺','Shop','id:'.$id)
            );
            return response()->json(['status'=>200]);
        }else{
            return response()->json(['message'=>'该商铺关联商品']);
        }

        //return Redirect('admin/shop');
    }


    public function toggleShow(){

        $this->shop_gate();

        $id = Input::get("id");
        $is_show = Shop::where("id",$id)->pluck("is_show");        
        $data = array();

        if($is_show==0){
            $data['is_show'] = 1;
            $data['id'] = $id;
            $res = Shop::where("id",$id)->update(['is_show'=>1]);
        }else{
            $data['is_show'] = 0;
            $data['id'] = $id;
            $res = Shop::where("id",$id)->update(['is_show'=>0]);
        }
        if($res != false){
            $data['info'] = true;           
        }else{
            $data['info'] = false;
        }
        return $data;

    }

    /**
     * 排序
     * @route admin.shop.sort
     * @return Response
     */
    public function sort(Request $request)
    {
        $this->shop_gate();

        //dd($request->all());
        $shop = $request->get('sort_order');
        //dd($goodsAttribute);

        if (is_array($shop)&&count($shop)>0)
        {
            foreach($shop as $k=>$v)
            {
                //dd($v);
                $sort_order = Shop::where('sort_order',$v)->get();
                //$sort_order=GoodsAttribute::find('sort_order');
                //dd($sort_order);
                Shop::find($k)->update(['sort_order' => $v]);


            }
        }

        return redirect('admin/shop');

    }
}
